import json
import time
from datetime import datetime

from websocket import WebSocketApp, create_connection
import threading

from util.jiafu_rest_api import RestApi
from util.const import WS_DEPTH, WS_TRADE, WS_USER
from util.jiafu_log import JiaFuLogger

log_file = JiaFuLogger("jiafu_server:util:jiafu_ws_api")


class WsApi:

    def on_message(self, ws, message):
        if self._callback:
            self._callback(message)
        if not self._ws:
            self._ws = ws

    def on_error(self, ws, error):
        log_file('ws %s error %s' % (self.type,str(error)))
        if self.keep_alive:
            if self._callback:
                self._callback({"errno":-2,"message":"连接出错"})
            time.sleep(5)
            self.run(self._symbol)

    def on_close(self, ws):
        log_file('ws %s close'%self.type)
        self.alive = False
        self._ws = None
        if self.keep_alive:
            if self._callback:
                self._callback({"errno":-2,"message":"连接关闭"})
            time.sleep(5)
            self.run(self._symbol)

    def on_open(self, ws):
        log_file('ws %s open' % self.type)
        # thread = threading.current_thread()
        # print("ws线程 %s"%thread.getName())
        self.alive = True
        if self._callback:
            self._callback({"errno": -100, "message": "连接成功"})
        if not self._ws:
            self._ws = ws

    def __init__(self, url,cookie, type):
        """
        :param cookie:已经登录的cookie，从rest_api里可以获得
        :param type:websocket连接的类型， 可取值：WS_DEPTH 深度推送
                                                 WS_TRADE 交易推送
                                                 WS_USER 账户更新推送
        """
        self._callback = None
        self._ws = None
        self._run_t = None
        self.type = type
        self._cookie = ''
        self.alive = False
        self._symbol = None
        if cookie:
            for key in cookie:
                self._cookie += key
                self._cookie += '='
                self._cookie += cookie[key]
                self._cookie += ';'
            self._cookie = self._cookie[:-1]
            self._base_url = url + type
        else:
            raise Exception('请先登录！')

    def run(self, symbol=None, message_recv_callback=None):
        """
        :param symbol: 如果是DEPTH和TRADE推送，则需要交易对
        :return:
        """
        self.keep_alive = True
        if self.type != WS_USER:
            self._final_url = self._base_url + symbol + "/"
            self._symbol=symbol
        else:
            self._final_url = self._base_url
        if self._ws:
            self._ws.close()
        if message_recv_callback:
            self._callback = message_recv_callback
        self._run_t = threading.Thread(target=self.__run__)
        self._run_t.start()

    def __run__(self):
        self._ws = WebSocketApp(self._final_url, on_message=self.on_message, on_close=self.on_close,
                                on_error=self.on_error,on_pong=self.on_pong,
                                cookie=self._cookie)
        self._ws.on_open = self.on_open
        self._ws.run_forever(ping_interval=20)


    def on_pong(self,ws,data):
        if self.keep_alive:
            ws.send('still alive')


    def close(self):
        self.keep_alive = False
        if self._ws != None:
            self._ws.close()



def callback(message):
    print('11111', datetime.now(), message)


def callback2(message):
    print('22222', datetime.now(), message)


if __name__ == "__main__":
    from const import GZ_REST_BASE_URL, GZ_WS_BASE_URL
    restApi = RestApi(GZ_REST_BASE_URL)
    res = restApi.login(name='600001', password='123456')
    if res['errno'] == 0:
        ws = WsApi(GZ_WS_BASE_URL, restApi.get_cookies(), WS_DEPTH)
        ws.run(symbol='ETHBTC', message_recv_callback=callback)

    print(res)
